<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/11/28 0028
 * Time: 17:29
 */

namespace logicmodel;


use comservice\Response;
use datamodel\BoxGoods;
use datamodel\BoxOrders;
use datamodel\GoodsOrders;
use datamodel\UsersBox;
use datamodel\UsersGoods;
use think\Db;

class TradeLogic
{
    private $goodsOrdersData;
    private $boxOrdersData;
    private $usersBoxData;
    private $usersGoodsData;

    public function __construct()
    {
        $this->goodsOrdersData = new GoodsOrders();
        $this->boxOrdersData = new BoxOrders();
        $this->usersGoodsData = new UsersGoods();
        $this->usersBoxData = new UsersBox();
    }

    /**
     * 交易市场作品列表
     * @param $search
     * @param $time_order
     * @param $price_order
     * @param $page
     * @param $pagesize
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tradeGoodsList($search,$time_order,$price_order,$page,$pagesize){
                $is_trade = config('site.is_trade');
        if($is_trade == 0) return Response::success('success',['data'=>[],'page'=>$page,'count'=>0,'pagesize'=>$pagesize]);
        $where['ug.is_del'] = 0;
        $where['ug.status'] = 2;
        $where['ug.is_show'] = 1;
        $where['u.is_del'] = 0;
        if(!empty($search)) $where['g.name'] = ['like','%'.$search.'%'];
        $count = $this->usersGoodsData->alias('ug')
            ->join('goods g','g.id = ug.goods_id')
            ->join('users u','u.id = ug.uid')
            ->join('author a','a.id = g.author_id')
            ->join('goods_category gc','gc.id = g.goods_category_id')
            ->join('network n','n.id = g.network_id')
            ->where($where)
            ->count();
        if($time_order > 0){
            if($time_order == 1){
                $order = ['ug.sales_time asc','ug.order asc'];
            }else{
                $order = ['ug.sales_time  desc','ug.order asc'];
            }

        }elseif ($price_order > 0){
            if($price_order == 1){
                $order = ['ug.price asc','ug.order asc'];
            }else{
                $order = ['ug.price desc','ug.order asc'];
            }
        }else{
            $order = ['ug.order asc'];
        }
        $field = ['g.name','g.image','g.desc','g.id','ug.price','u.nick_name','u.head_image','ug.id users_goods_id','a.name author_name','a.image auther_image'];
        $data = $this->usersGoodsData->alias('ug')
            ->join('goods g','g.id = ug.goods_id')
            ->join('users u','u.id = ug.uid')
            ->join('author a','a.id = g.author_id')
            ->join('goods_category gc','gc.id = g.goods_category_id')
            ->join('network n','n.id = g.network_id')
            ->where($where)
            ->order($order)
            ->field($field)
            ->page($page,$pagesize)
            ->select();
        if(!empty($data)){
            $data = collection($data)->toArray();
            $data = addWebSiteUrl($data,['image','head_image','auther_image']);
        }
        return Response::success('success',['data'=>$data,'page'=>$page,'count'=>$count,'pagesize'=>$pagesize]);
    }

    /**
     * 交易市场商品详情
     * @param $users_goods_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsDetail($users_goods_id){
        $where['ug.is_del'] = 0;
        $where['ug.status'] = 2;
        $where['ug.is_show'] = 1;
        $where['u.is_del'] = 0;
        $where['ug.id'] = $users_goods_id;
        $field = ['g.*','ug.price','a.name author_name','a.image author_image','u.nick_name','u.head_image','ug.id users_goods_id','ug.price','n.name network_name'];
        $data = $this->usersGoodsData->alias('ug')
            ->join('goods g','g.id = ug.goods_id')
            ->join('users u','u.id = ug.uid')
            ->join('author a','a.id = g.author_id')
            ->join('goods_category gc','gc.id = g.goods_category_id')
            ->join('network n','n.id = g.network_id')
            ->where($where)
            ->field($field)
            ->find();
        if(!empty($data)) {
            $data = $data->toArray();
            $data = addWebSiteUrl($data,['image','author_image']);
            return Response::success('success',$data);
        }
        return Response::fail('作品信息错误');
    }


    /**
     * 盲盒出售列表
     * @param $search
     * @param $time_order
     * @param $price_order
     * @param int $page
     * @param int $pagesize
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tradeBoxList($search,$time_order,$price_order,$page=1,$pagesize=10){
        $is_trade = config('site.is_trade');
        if($is_trade == 0) return Response::success('success',['data'=>[],'page'=>$page,'count'=>0,'pagesize'=>$pagesize]);
        $where['ub.is_del'] = 0;
        $where['ub.status'] = 2;
        $where['ub.is_show'] = 1;
        $where['u.is_del'] = 0;
        if(!empty($search)) $where['b.name'] = ['like','%'.$search.'%'];
        $count = $this->usersBoxData->alias('ub')
            ->join('box b','b.id = ub.box_id')
            ->join('users u','u.id = ub.uid')
            ->where($where)
            ->count();
        $field = ['b.name','b.image','ub.price','u.nick_name','u.head_image','b.id','ub.id users_box_id'];

        if($time_order > 0){
            if($time_order == 1){
                $order = ['ub.sales_time desc','ub.order desc'];
            }else{
                $order = ['ub.sales_time  asc','ub.order desc'];
            }

        }elseif ($price_order > 0){
            if($price_order == 1){
                $order = ['ub.price desc','ub.order desc'];
            }else{
                $order = ['ub.price asc','ub.order desc'];
            }
        }else{
            $order = ['ub.order desc'];
        }
        $data = $this->usersBoxData->alias('ub')
            ->join('box b','b.id = ub.box_id')
            ->join('users u','u.id = ub.uid')
            ->where($where)
            ->order($order)
            ->field($field)
            ->page($page,$pagesize)
            ->select();
        if(!empty($data)){
            $data = collection($data)->toArray();
            $data = addWebSiteUrl($data,['image','head_image']);
        }
        return Response::success('success',['data'=>$data,'page'=>$page,'count'=>$count,'pagesize'=>$pagesize]);
    }
    /**
     * 盲盒详情
     * @param $users_box_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function boxDetail($users_box_id){
        $where['ub.is_del'] = 0;
        $where['ub.status'] = 2;
        $where['ub.is_show'] = 1;
        $where['u.is_del'] = 0;
        $where['ub.id'] = $users_box_id;
        $field = ['b.*','ub.price','u.nick_name','u.head_image','ub.id users_box_id','ub.price'];
        $data = $this->usersBoxData->alias('ub')
            ->join('box b','b.id = ub.box_id')
            ->join('users u','u.id = ub.uid')
            ->where($where)
            ->field($field)
            ->find();
        if(empty($data)) return Response::fail('作品信息错误');
        $data = $data->toArray();
        $data =  addWebSiteUrl($data,['image','head_image']);
        $goods = (new BoxGoods())->alias('bg')
            ->join('goods g','g.id = bg.goods_id')
            ->where(['bg.box_id'=>$data['id'],'bg.is_show'=>1,'bg.is_del'=>0])
            ->field(['bg.rate','g.name','g.image','g.label','g.price'])
            ->order('bg.order asc')
            ->select();
        if(!empty($goods)){
            $goods = collection($goods)->toArray();
            $goods = addWebSiteUrl($goods,['image']);
            $data['goods'] = $goods;
        }else{
            $data['goods'] = [];
        }
        return Response::success('success',$data);
    }

    /**
     * 购买市场作品
     * @param $userInfo
     * @param $users_goods_id
     * @param $pay_type
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function tradeGoods($userInfo,$users_goods_id,$pay_type){
        if($userInfo['is_auth'] == 0) return Response::bindAuth();
        $uid = $userInfo['id'];
        $where['ug.status'] = 2;
        $where['ug.is_show'] = 1;
        $where['ug.id'] = $users_goods_id;
        $field = ['ug.*','g.name'];
        $info =  $this->usersGoodsData->alias('ug')
            ->join('goods g','g.id = ug.goods_id')
            ->field($field)
            ->where($where)
            ->find();
        if(empty($info)) return Response::fail('作品已被抢购');
        if($info['uid'] == $uid)    return Response::fail('您不能与自己的作品交易');
        $price = $info['price'];
        $time = date('Y-m-d H:i:s');
        $order_num = uniqueNum();
        //生成订单
        if($pay_type == 1){
            Db::startTrans();
            $accountLogic = new AccountLogic();
            $result =  $accountLogic->subAccount($uid,1,$price,'购买作品','购买作品'.$info['name'].'扣款');
            if(!$result){
                Db::rollback();
                return Response::fail('余额不足');
            }
            $result = $accountLogic->addAccount($info['uid'],1,$price,'出售作品','出售作品'.$info['name'].'收益');
            if(!$result){
                Db::rollback();
                return Response::fail('交易失败');
            }

            //生成订单
            $result = $this->usersGoodsData->updateByWhere(['id'=>$users_goods_id],['status'=>4]);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $order['order_num'] = $order_num;
            $order['goods_num'] = $info['goods_num'];
            $order['users_goods_id'] = $users_goods_id;
            $order['goods_id'] = $info['goods_id'];
            $order['buy_uid'] = $uid;
            $order['sale_uid'] = $info['uid'];
            $order['pay_type'] = $pay_type;
            $order['price'] = $price;
            $order['status'] = 1;
            $order['pay_time'] = $time;
            $order['create_time'] = $time;
            $result =  $this->goodsOrdersData->insertGetId($order);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $goods['uid'] = $uid;
            $goods['price'] = $price;
            $goods['goods_id'] = $info['goods_id'];
            $goods['create_time'] = $time;
            $result = $this->usersGoodsData->insertGetId($goods);
            if($result){
                Db::commit();
                return Response::success('购买成功',['is_pay'=>1]);
            }
            Db::rollback();
            return Response::fail('购买失败');
        }elseif($pay_type == 2){
            if($userInfo['is_wx_auth'] == 0 || empty($userInfo['wx_open_id'])) return Response::wxAuth();
            $pay =  (new WxLogic())->pay($order_num,'购买NFT'.$info['name'],$price,$userInfo['wx_open_id'],config('site.wx_goods_orders_notify'));
            if($pay === false) return Response::fail('订单生成失败');
            Db::startTrans();
            //生成订单
            $result = $this->usersGoodsData->updateByWhere(['id'=>$users_goods_id],['status'=>3]);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $order['order_num'] = $order_num;
            $order['goods_num'] = $info['goods_num'];
            $order['users_goods_id'] = $users_goods_id;
            $order['goods_id'] = $info['goods_id'];
            $order['buy_uid'] = $uid;
            $order['sale_uid'] = $info['uid'];
            $order['pay_type'] = $pay_type;
            $order['price'] = $price;
            $order['status'] = 0;
            $order['create_time'] = $time;
            $result =  $this->goodsOrdersData->insertGetId($order);
            if($result){
                Db::commit();
                return Response::success('购买成功',['is_pay'=>0,'pay'=>$pay]);
            }
            Db::rollback();
            return Response::fail('购买失败');
        }elseif($pay_type == 3){
            //微信APP支付
            $notify_url = config('site.wx_app_goods_orders_notify');
            $pay =  (new WxLogic())->appPay($order_num,'购买藏品'.$info['name'],$price,$notify_url);
            if($pay === false) return Response::fail('订单生成失败');
            Db::startTrans();
            //生成订单
            $result = $this->usersGoodsData->updateByWhere(['id'=>$users_goods_id],['status'=>3]);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $order['order_num'] = $order_num;
            $order['goods_num'] = $info['goods_num'];
            $order['users_goods_id'] = $users_goods_id;
            $order['goods_id'] = $info['goods_id'];
            $order['buy_uid'] = $uid;
            $order['sale_uid'] = $info['uid'];
            $order['pay_type'] = $pay_type;
            $order['price'] = $price;
            $order['status'] = 0;
            $order['create_time'] = $time;
            $result =  $this->goodsOrdersData->insertGetId($order);
            if($result){
                Db::commit();
                return Response::success('购买成功',['is_pay'=>0,'pay'=>$pay]);
            }
            Db::rollback();
            return Response::fail('购买失败');
        }elseif($pay_type == 4){
            $notify_url = config('site.ali_app_goods_orders_notify');
            $pay =  (new AliLogic())->appPay($order_num,'购买藏品'.$info['name'],$price,$notify_url);
            if($pay === false) return Response::fail('订单生成失败');
            Db::startTrans();
            //生成订单
            $result = $this->usersGoodsData->updateByWhere(['id'=>$users_goods_id],['status'=>3]);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $order['order_num'] = $order_num;
            $order['goods_num'] = $info['goods_num'];
            $order['users_goods_id'] = $users_goods_id;
            $order['goods_id'] = $info['goods_id'];
            $order['buy_uid'] = $uid;
            $order['sale_uid'] = $info['uid'];
            $order['pay_type'] = $pay_type;
            $order['price'] = $price;
            $order['status'] = 0;
            $order['create_time'] = $time;
            $result =  $this->goodsOrdersData->insertGetId($order);
            if($result){
                Db::commit();
                return Response::success('购买成功',['is_pay'=>0,'pay'=>$pay]);
            }
            Db::rollback();
            return Response::fail('购买失败');
        }else{
            return  Response::fail('请选择支付方式');
        }
    }

    /**
     * 市场盲盒
     * @param $userInfo
     * @param $users_box_id
     * @param $pay_type
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function tradeBox($userInfo,$users_box_id,$pay_type){
        if($userInfo['is_auth'] == 0) return Response::bindAuth();
        $uid = $userInfo['id'];
        $where['ub.status'] = 2;
        $where['ub.is_show'] = 1;
        $where['ub.id'] = $users_box_id;
        $field = ['ub.*','b.name'];
        $info =  $this->usersBoxData->alias('ub')
            ->join('box b','b.id = ub.box_id')
            ->field($field)
            ->where($where)
            ->find();
        if(empty($info)) return Response::fail('作品已被抢购');
        if($info['uid'] == $uid)    return Response::fail('您不能与自己的盲盒交易');
        $price = $info['price'];
        $time = date('Y-m-d H:i:s');
        $order_num = uniqueNum();
        //生成订单
        if($pay_type == 1){
            Db::startTrans();
              $accountLogic = new AccountLogic();
            $result =  $accountLogic->subAccount($uid,1,$price,'购买盲盒','购买盲盒'.$info['name'].'扣款');
            if(!$result){
                Db::rollback();
                return Response::fail('余额不足');
            }
            $result = $accountLogic->addAccount($info['uid'],1,$price,'出售盲盒','出售盲盒'.$info['name'].'收益');
            if(!$result){
                Db::rollback();
                return Response::fail('交易失败');
            }
            //生成订单
            $result = $this->usersBoxData->updateByWhere(['id'=>$users_box_id],['status'=>4,'sales_time'=>$time]);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $order['order_num'] = $order_num;
            $order['users_box_id'] = $users_box_id;
            $order['box_id'] = $info['box_id'];
            $order['buy_uid'] = $uid;
            $order['sale_uid'] = $info['uid'];
            $order['pay_type'] = $pay_type;
            $order['price'] = $price;
            $order['status'] = 1;
            $order['pay_time'] = $time;
            $order['create_time'] = $time;
            $result =  $this->boxOrdersData->insertGetId($order);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $box['uid'] = $uid;
            $box['price'] = $price;
            $box['box_id'] = $info['box_id'];
            $box['create_time'] = $time;
            $result = $this->usersBoxData->insertGetId($box);
            if($result){
                Db::commit();
                return Response::success('购买成功',['is_pay'=>1]);
            }
            Db::rollback();
            return Response::fail('购买失败');
        }elseif($pay_type == 2){
            if($userInfo['is_wx_auth'] == 0 || empty($userInfo['wx_open_id'])) return Response::wxAuth();
            $pay =  (new WxLogic())->pay($order_num,'购买NFT'.$info['name'],$price,$userInfo['wx_open_id'],config('site.wx_box_orders_notify'));
            if($pay === false) return Response::fail('订单生成失败');
            Db::startTrans();
            //生成订单
            $result = $this->usersBoxData->updateByWhere(['id'=>$users_box_id],['status'=>3]);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $order['order_num'] = $order_num;
            $order['users_box_id'] = $users_box_id;
            $order['box_id'] = $info['box_id'];
            $order['buy_uid'] = $uid;
            $order['sale_uid'] = $info['uid'];
            $order['pay_type'] = $pay_type;
            $order['price'] = $price;
            $order['status'] = 0;
            $order['create_time'] = $time;
            $result =  $this->boxOrdersData->insertGetId($order);
            if($result){
                Db::commit();
                return Response::success('购买成功',['is_pay'=>0,'pay'=>$pay]);
            }
            Db::rollback();
            return Response::fail('购买失败');
        }elseif($pay_type == 3){
            $notify_url = config('site.wx_app_box_orders_notify');
            $pay =  (new WxLogic())->appPay($order_num,'购买NFT'.$info['name'],$price,$notify_url);
            if($pay === false) return Response::fail('订单生成失败');
            Db::startTrans();
            //生成订单
            $result = $this->usersBoxData->updateByWhere(['id'=>$users_box_id],['status'=>3]);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $order['order_num'] = $order_num;
            $order['users_box_id'] = $users_box_id;
            $order['box_id'] = $info['box_id'];
            $order['buy_uid'] = $uid;
            $order['sale_uid'] = $info['uid'];
            $order['pay_type'] = $pay_type;
            $order['price'] = $price;
            $order['status'] = 0;
            $order['create_time'] = $time;
            $result =  $this->boxOrdersData->insertGetId($order);
            if($result){
                Db::commit();
                return Response::success('购买成功',['is_pay'=>0,'pay'=>$pay]);
            }
            Db::rollback();
            return Response::fail('购买失败');
        }elseif($pay_type == 4){
            $notify_url = config('site.ali_app_box_orders_notify');
            $pay =  (new AliLogic())->appPay($order_num,'购买NFT'.$info['name'],$price,$notify_url);
            if($pay === false) return Response::fail('订单生成失败');
            Db::startTrans();
            //生成订单
            $result = $this->usersBoxData->updateByWhere(['id'=>$users_box_id],['status'=>3]);
            if(!$result){
                Db::rollback();
                return Response::fail('购买失败');
            }
            $order['order_num'] = $order_num;
            $order['users_box_id'] = $users_box_id;
            $order['box_id'] = $info['box_id'];
            $order['buy_uid'] = $uid;
            $order['sale_uid'] = $info['uid'];
            $order['pay_type'] = $pay_type;
            $order['price'] = $price;
            $order['status'] = 0;
            $order['create_time'] = $time;
            $result =  $this->boxOrdersData->insertGetId($order);
            if($result){
                Db::commit();
                return Response::success('购买成功',['is_pay'=>0,'pay'=>$pay]);
            }
            Db::rollback();
            return Response::fail('购买失败');
        }else{
            return  Response::fail('请选择支付方式');
        }


    }
}